﻿using StackExchange.Profiling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace ImageWeb
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            StackExchange.Profiling.EntityFramework6.MiniProfilerEF6.Initialize();            
            FluentScheduler.JobManager.Initialize(new ImageWeb.ScheduleJob());
            log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(Server.MapPath("~/Web.config")));
        }
        protected void Application_End(object sender, EventArgs e)
        {
            FluentScheduler.JobManager.Initialize(new ImageWeb.ScheduleJob());
        }
        protected void Application_BeginRequest()
        {
            if (Request.IsLocal)//这里是允许本地访问启动监控,可不写
            {
                MiniProfiler.Start();

            }
        }

        protected void Application_EndRequest()
        {
            MiniProfiler.Stop();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            HttpException httpException = exception as HttpException;

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");

            switch (httpException.GetHttpCode())
            {
                case 404:
                    routeData.Values.Add("action", "HttpError404");
                    break;
                default:
                    Response.Write("系统出错");
                    break;
            }

            Response.Clear();
            Server.ClearError();
            Response.TrySkipIisCustomErrors = true;
            IController errorController = new ImageWeb.Controllers.ErrorController();
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

            //Response.RedirectToRoute(new { controller = "Error", action = "HttpError404" });
        }
    }
}
